package com.mlethe.library.imagepreview;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.activity.EdgeToEdge;
import androidx.annotation.CallSuper;
import androidx.annotation.NonNull;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;

import com.mlethe.library.imagepreview.enitity.IThumbViewInfo;
import com.mlethe.library.imagepreview.loader.OnApplyViewInsetsListener;
import com.mlethe.library.imagepreview.view.BasePhotoFragment;
import com.mlethe.library.imagepreview.wight.BezierBannerView;
import com.mlethe.library.imagepreview.wight.SmoothImageView;

import java.util.List;

/**
 * Created by Mlethe on 2017/4/26.
 * Deprecated:图片预览页面
 */
public class GPreviewActivity extends FragmentActivity {

    private PhotoPagerAdapter mAdapter = new PhotoPagerAdapter(this);

    protected boolean isTransformOut = false;
    /**
     * 图片的地址
     */
    private List<IThumbViewInfo> imgUrls;
    /**
     * 当前图片的位置
     */
    protected int currentIndex;
    /**
     * 当前位置（进入时传入的值）
     */
    protected int currentPosition;
    /**
     * 图片的展示的Fragment类
     */
    protected Class<? extends BasePhotoFragment> fragmentClazz;
    /**
     * 展示图片的viewPager
     */
    private ViewPager2 viewPager;
    /**
     * 显示图片数
     */
    private TextView ltAddDot;
    /**
     * 指示器控件
     */
    private BezierBannerView bezierBannerView;
    /**
     * 指示器类型枚举
     */
    private GPreviewBuilder.IndicatorType type;
    /**
     * 是否自定义数据
     */
    private boolean isCustomData = false;
    /**
     * 当为一张图片时 是否显示指示器  默认显示
     */
    private boolean isShow = true;
    /**
     * 点击超出内容是否退出（黑色区域）
     */
    private boolean isSingleFling = false;
    /**
     * 是否禁用拖拽返回
     */
    private boolean isDrag = false;
    /**
     * sensitivity MAX_TRANS_SCALE 的值来控制图片拖拽返回灵敏度。
     */
    private float sensitivity = 0.5f;
    /**
     * 图片没有放大或者的缩小状态时，点击超出内容区域是否禁止退出
     */
    private boolean isScale = true;
    /**
     * 图片没有放大或者的缩小状态触退出时，点击超出内容区域
     */
    private int scaleCount = 3;
    /**
     * 是否全屏
     */
    private boolean isFullscreen = false;
    /**
     * viewPager 与屏幕顶部的距离（px）
     */
    private int viewPageTop = 0;
    /**
     * 是否执行过进入动画
     */
    private boolean isTransformIn;

    private final ViewPager2.OnPageChangeCallback mPageChangeCallback = new ViewPager2.OnPageChangeCallback() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        }

        @Override
        public void onPageSelected(int position) {
            //当被选中的时候设置小圆点和当前位置
            if (isFinishing()) return;
            if (ltAddDot != null) {
                ltAddDot.setText(getString(R.string.string_count, (position + 1), imgUrls.size()));
            }
            currentIndex = position;
            onSelected(position, imgUrls.get(position));
        }

        @Override
        public void onPageScrollStateChanged(int state) {
        }
    };

    @CallSuper
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (!initData()) {
            finish();
            return;
        }
        View view = getView();
        OnApplyViewInsetsListener viewInsetsListener;
        if (view == null) {
            view = getLayoutInflater().inflate(R.layout.activity_image_preview_photo, null);
            View vp = view.findViewById(R.id.viewPager);
            View statusBarView = view.findViewById(R.id.statusBarView);
            View navigationBarView = view.findViewById(R.id.navigationBarView);
            viewInsetsListener = new OnApplyViewInsetsListener() {

                boolean isUpdate = false;

                @Override
                public void onApplyViewInsets(View v, Insets insets) {
                    if (isUpdate) return;
                    isUpdate = true;
                    navigationBarView.setPadding(0, 0, 0, insets.bottom);
                    if (!isFullscreen) {
                        statusBarView.setPadding(0, insets.top, 0, 0);
                        statusBarView.setBackgroundColor(Color.BLACK);
                        navigationBarView.setBackgroundColor(Color.BLACK);
                        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) vp.getLayoutParams();
                        layoutParams.setMargins(layoutParams.leftMargin, layoutParams.topMargin, layoutParams.rightMargin, insets.bottom);
                        vp.setLayoutParams(layoutParams);
                        return;
                    }
                    navigationBarView.setBackgroundColor(Color.TRANSPARENT);
                }
            };
        } else {
            viewInsetsListener = getOnApplyViewInsetsListener(view);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.VANILLA_ICE_CREAM) {
            ViewCompat.setOnApplyWindowInsetsListener(view, (v, insets) -> {
                Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars() | WindowInsetsCompat.Type.displayCutout());
                if (viewInsetsListener != null) {
                    viewInsetsListener.onApplyViewInsets(v, systemBars);
                }
                return insets;
            });
        }
        setContentView(view);
        initView();
    }

    @Override
    protected void onDestroy() {
        ZoomMediaLoader.getInstance().getLoader().clearMemory(this);
        ltAddDot = null;
        if (bezierBannerView != null) {
            bezierBannerView.detachedToViewPager(viewPager);
            bezierBannerView = null;
        }
        if (viewPager != null) {
            viewPager.setAdapter(null);
            viewPager.unregisterOnPageChangeCallback(mPageChangeCallback);
            viewPager.removeAllViews();
            viewPager = null;
        }
        mAdapter = null;
        if (imgUrls != null) {
            imgUrls.clear();
            imgUrls = null;
        }
        super.onDestroy();
    }

    /**
     * 初始化数据
     */
    private boolean initData() {
        Intent intent = getIntent();
        isCustomData = intent.getBooleanExtra("isCustomData", false);
        if (!isCustomData) {
            imgUrls = intent.getParcelableArrayListExtra("imagePaths");
            if (imgUrls == null || imgUrls.isEmpty()) {
                return false;
            }
        }
        currentIndex = intent.getIntExtra("position", -1);
        currentPosition = currentIndex;
        type = (GPreviewBuilder.IndicatorType) intent.getSerializableExtra("type");
        isShow = intent.getBooleanExtra("isShow", true);
        isSingleFling = intent.getBooleanExtra("isSingleFling", false);
        isDrag = intent.getBooleanExtra("isDrag", false);
        sensitivity = intent.getFloatExtra("sensitivity", 0.5f);
        isScale = intent.getBooleanExtra("isScale", true);
        scaleCount = intent.getIntExtra("scaleCount", 3);
        isFullscreen = intent.getBooleanExtra("isFullscreen", false);
        int duration = intent.getIntExtra("duration", 300);
        if (isFullscreen) {
            Window window = getWindow();
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.VANILLA_ICE_CREAM) {
                EdgeToEdge.enable(this);
                window.setNavigationBarContrastEnforced(false);
            } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                // 状态栏透明
                window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
                int flag = View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    flag = flag | View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR;
                }
                window.getDecorView().setSystemUiVisibility(flag);
                window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
                window.setStatusBarColor(Color.TRANSPARENT);
                window.setNavigationBarColor(Color.BLACK);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                    // 异形屏延伸显示区域
                    WindowManager.LayoutParams params = window.getAttributes();
                    params.layoutInDisplayCutoutMode =
                            WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES;
                    window.setAttributes(params);
                }
            }
        }
        try {
            SmoothImageView.setDuration(duration);
            fragmentClazz = (Class<? extends BasePhotoFragment>) intent.getSerializableExtra("className");
        } catch (Exception e) {
            fragmentClazz = BasePhotoFragment.class;
        }
        return true;
    }

    /**
     * 初始化控件
     */
    private void initView() {
        viewPager = findViewById(R.id.viewPager);
        View view = viewPager.getChildAt(0);
        if (view instanceof RecyclerView) {
            RecyclerView recyclerView = (RecyclerView) view;
            recyclerView.setOverScrollMode(View.OVER_SCROLL_NEVER);
        }
        viewPager.setOffscreenPageLimit(1);
        // viewPager的适配器
        viewPager.setAdapter(mAdapter);
        viewPager.registerOnPageChangeCallback(mPageChangeCallback);
        viewPager.setCurrentItem(currentIndex, false);
        bezierBannerView = findViewById(R.id.bezierBannerView);
        ltAddDot = findViewById(R.id.ltAddDot);
        if (bezierBannerView != null) {
            bezierBannerView.setVisibility(View.GONE);
        }
        if (ltAddDot != null) {
            ltAddDot.setVisibility(View.GONE);
        }
        viewPager.post(new Runnable() {
            @Override
            public void run() {
                if (isFinishing()) return;
                Rect bounds = new Rect();
                viewPager.getGlobalVisibleRect(bounds);
                viewPageTop = bounds.top;
                if (isTransformIn) return;
                FragmentManager fragmentManager = getSupportFragmentManager();
                Fragment fragment = fragmentManager.findFragmentByTag("f" + currentIndex);
                if (fragment instanceof BasePhotoFragment) {
                    isTransformIn = true;
                    BasePhotoFragment currentFragment = (BasePhotoFragment) fragment;
                    currentFragment.setViewPageTop(viewPageTop);
                    onEnterAnimationStart();
                    currentFragment.transformIn(new SmoothImageView.onTransformListener() {
                        @Override
                        public void onTransformStart() {
                        }

                        @Override
                        public void onTransformCompleted(SmoothImageView.Status status) {
                            if (isFinishing()) return;
                            renderView();
                            onEnterAnimationEnd();
                        }
                    });
                } else if (fragmentManager.getFragments().size() > 0) {
                    onEnterAnimationEnd();
                }
            }
        });
    }

    /**
     * 渲染view
     */
    private void renderView() {
        int imgSize = imgUrls == null ? 0 : imgUrls.size();
        if (imgSize <= 0 || imgSize == 1 && !isShow) return;
        if (type == GPreviewBuilder.IndicatorType.Dot) {
            if (bezierBannerView != null) {
                bezierBannerView.setVisibility(View.VISIBLE);
                bezierBannerView.attachToViewpager(viewPager);
            }
        } else if (ltAddDot != null) {
            ltAddDot.setVisibility(View.VISIBLE);
            ltAddDot.setText(getString(R.string.string_count, (currentIndex + 1), imgSize));
        }
    }

    /***退出预览的动画***/
    public void transformOut() {
        if (isTransformOut) return;
        if (viewPager != null) {
            viewPager.setEnabled(false);
        }
        isTransformOut = true;
        Fragment fragment = getSupportFragmentManager().findFragmentByTag("f" + currentIndex);
        if (fragment instanceof BasePhotoFragment) {
            BasePhotoFragment currentFragment = (BasePhotoFragment) fragment;
            if (ltAddDot != null) {
                ltAddDot.setVisibility(View.GONE);
            }
            if (bezierBannerView != null) {
                bezierBannerView.setVisibility(View.GONE);
            }
            onFinishAnimationStart();
            currentFragment.changeBg(Color.TRANSPARENT);
            currentFragment.setViewPageTop(viewPageTop);
            currentFragment.transformOut(new SmoothImageView.onTransformListener() {
                @Override
                public void onTransformStart() {
                }

                @Override
                public void onTransformCompleted(SmoothImageView.Status status) {
                    if (viewPager != null) {
                        viewPager.setEnabled(true);
                    }
                    exit();
                }
            });
        } else {
            exit();
        }
    }

    @Override
    public void finish() {
        BasePhotoFragment.listener = null;
        super.finish();
    }

    /**
     * 设置数据源
     *
     * @param list
     */
    public final <E extends IThumbViewInfo> void setImgUrls(List<E> list) {
        if (!isCustomData) return;
        if (list == null || list.isEmpty()) {
            finish();
            return;
        }
        imgUrls = (List<IThumbViewInfo>) list;
        if (mAdapter != null) {
            mAdapter.notifyDataSetChanged();
        }
        if (viewPager != null) {
            viewPager.setCurrentItem(currentPosition, false);
        }
        renderView();
        if (isTransformIn) return;
        viewPager.post(new Runnable() {
            @Override
            public void run() {
                if (isFinishing() || isTransformIn) return;
                FragmentManager fragmentManager = getSupportFragmentManager();
                Fragment fragment = fragmentManager.findFragmentByTag("f" + currentIndex);
                if (fragment instanceof BasePhotoFragment) {
                    isTransformIn = true;
                    BasePhotoFragment currentFragment = (BasePhotoFragment) fragment;
                    currentFragment.setViewPageTop(viewPageTop);
                    onEnterAnimationStart();
                    currentFragment.transformIn(new SmoothImageView.onTransformListener() {
                        @Override
                        public void onTransformStart() {
                        }

                        @Override
                        public void onTransformCompleted(SmoothImageView.Status status) {
                            if (isFinishing()) return;
                            renderView();
                            onEnterAnimationEnd();
                        }
                    });
                } else {
                    onEnterAnimationEnd();
                }
            }
        });
    }

    /***
     * 获取图片地址集合
     * @return List
     * **/
    public final List<IThumbViewInfo> getImgUrls() {
        return imgUrls;
    }

    /**
     * 关闭页面
     */
    private void exit() {
        onFinishAnimationEnd();
        finish();
        overridePendingTransition(0, 0);
    }

    /***
     * 得到 ViewPager2
     * @return ViewPager2
     * **/
    public ViewPager2 getViewPager() {
        return viewPager;
    }

    /***
     * 自定义布局内容
     * @return int
     ***/
    public View getView() {
        return null;
    }

    /***
     * 获取 OnApplyViewInsetsListener
     * @return int
     ***/
    public OnApplyViewInsetsListener getOnApplyViewInsetsListener(View view) {
        return null;
    }

    /**
     * 进入动画开始
     */
    public void onEnterAnimationStart() {
    }

    /**
     * 进入动画结束
     */
    public void onEnterAnimationEnd() {
    }

    /**
     * 退出动画开始
     */
    public void onFinishAnimationStart() {
    }

    /**
     * 退出动画结束
     */
    public void onFinishAnimationEnd() {
    }

    /**
     * 滑动选中的回调
     *
     * @param position
     * @param data
     */
    public void onSelected(int position, @NonNull IThumbViewInfo data) {
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            isTransformOut = false;
            transformOut();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * pager的适配器
     */
    private class PhotoPagerAdapter extends FragmentStateAdapter {

        PhotoPagerAdapter(@NonNull FragmentActivity fragmentActivity) {
            super(fragmentActivity);
        }

        @NonNull
        @Override
        public Fragment createFragment(int position) {
            return BasePhotoFragment.getInstance(
                    fragmentClazz,
                    imgUrls.get(position),
                    currentPosition == position,
                    isSingleFling,
                    isDrag,
                    sensitivity,
                    isScale,
                    scaleCount,
                    isFullscreen
            );
        }

        @Override
        public int getItemCount() {
            return imgUrls == null ? 0 : imgUrls.size();
        }
    }


}
